// axios中的默认配置项
const defaults = {
	timeout: 0
}

class Axios {
	constructor(instanceConfig) {
		this.defaults = instanceConfig;
	}
	
	request(configOrUrl = {}, config = {}) {
		// 判断configOrUrl是否为地址
		if (typeof configOrUrl === "string") {
			// 将地址作为配置对象中的url属性值
			config.url = configOrUrl;
		} else {
			// 将configOrUrl作为配置对象处理
			config = configOrUrl;
		}
		config = {
			...this.defaults,
			...config
		};
		config.method = (config.method || "get").toLowerCase();
		const _dispatchRequest = function () {
			return new Promise((resolve, reject) => {
				const request = new XMLHttpRequest();
				request.responseType = "json";
				request.open(config.method, config.url);
				request.send();
				request.onload = function () {
					if(request.status === 200){
						resolve({
							config,
							data:request.response,
							headers:request.getAllResponseHeaders(),
							request,
							status:request.status,
							statusText:request.statusText
						})
					}else{
						reject({
							code:"ERR_BAD_REQUEST",
							config,
							message:"Request failed with status code "+request.status,
							name:"AxiosError",
							request,
							response:request.response
						})
					}
					
				}
				request.onerror = function (err) {
					reject({
						code: "ERR_NETWORK",
						config,
						message: "Network Error",
						name: "AxiosError",
						request
					})
				}
			})
		}
		return _dispatchRequest()
	}
}

function createInstance(defaultConfig) {
	// 实例化Axios类，得到的实例赋值给常量context
	const context = new Axios(defaultConfig);
	// 将Axios.prototype.request函数中的this绑定为context,赋值给常量instance
	const instance = Axios.prototype.request.bind(context)
	return instance;
}

const axios = createInstance(defaults);
export default axios;